#include "tc_man.h"
#include "tc_thread.h"

tc_man::tc_man(tc_sink* sink)
{
	m_sink = sink;
	m_thread = new tc_thread(m_sink);
	m_thread->InitThread(false);
	m_log = new logfile("tc_man");
};

tc_man::~tc_man()
{
	delete m_log;
	m_thread->StopThread();
	delete m_thread;
};

bool tc_man::add_socket(uint32* socket,ip_node task)
{
	m_lock.EnterLock();
	std::map<uint32, tcp_node*>::iterator iter;
	iter = m_nodemap.find(*socket);

	if(iter == m_nodemap.end())
	{
		uint16  port = task.d_port;
		tcp_client* client = new tcp_client(task.d_ip,task.d_port);
		if(client->get_socket() == -1)
		{
			m_log->WriteTrace("no socket to new");
			m_lock.LeaveLock();
			return false;
		}

	   client->con();

	   tcp_node* new_node = new tcp_node;
	   new_node->d_ip = task.d_ip;
	   new_node->d_port = task.d_port;
	   new_node->l_port  = task.l_port;
	   new_node->s_socket = client;
	   m_thread->add_socket(new_node->s_socket->get_socket());
	   *socket = new_node->s_socket->get_socket();

	   if(*socket == 0)
		   m_log->WriteTrace("add socket is error");

	   m_nodemap.insert(std::map<uint32, tcp_node*>::value_type
			(*socket,new_node));

	   m_lock.LeaveLock();
	   return true;
	}

	m_log->WriteTrace("find this socket");
	m_lock.LeaveLock();
	return false;
};

bool tc_man::del_socket(uint32 socket)
{
	m_lock.EnterLock();
	std::map<uint32,tcp_node*>::iterator iter;
	iter = m_nodemap.find(socket);
	
	if(iter != m_nodemap.end())
	{
		char tmp_str[1023] = {0};
		sprintf(tmp_str,"delete socket=%d",socket);
		m_log->WriteTrace(tmp_str);
		m_thread->del_socket(iter->second->s_socket->get_socket());
		delete iter->second->s_socket;
		delete iter->second;
		m_nodemap.erase(iter);
		m_lock.LeaveLock();
		return true;
	}
	
	char tmp_str[1023] = {0};
	sprintf(tmp_str,"delete socket=%d",socket);
	m_log->WriteTrace(tmp_str);
	m_lock.LeaveLock();
	return false;
};

int tc_man::send_buf(uint32 socket,char* buf, uint32 buf_size)
{
	m_lock.EnterLock();
	std::map<uint32,tcp_node*>::iterator iter;
	iter = m_nodemap.find(socket);
	if(iter == m_nodemap.end())
	{
        m_log->WriteTrace("find socket error");
        m_lock.LeaveLock();
		return false;
	}

    int size = iter->second->s_socket->sendbuf(buf,buf_size);

	m_lock.LeaveLock();    
    return size;
}




